/*
 * BanBu_TextAndTags
 * @description 本文件提供发广播时填写文字和标签界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供发广播时填写文字和标签界面的ViewController
 */

#import "BanBu_TextAndTags.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "TKLoadingView.h"
#import "RecordAudio.h"
#import "BanBu_BroadcastTVC.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "QVerifyWebViewController.h"
#import "BanBu_MagicCastViewController.h"
@interface BanBu_TextAndTags ()

@end

@implementation BanBu_TextAndTags
- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (NSString *)loadAccessToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}
-(void)dealloc{
    
    [_soundTime release],_soundTime = nil;
    [_imageString release],_imageString = nil;
    [_imageData release],_imageData = nil;
    [_soundData release],_soundData = nil;
    self.functionView = nil;
    [super dealloc];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    BanBu_ImageView *img = [[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable];
    img.frame = CGRectMake(0, 0, 320, __MainScreen_Height-44);
    [self.view addSubview:img];
    [img release];
    
    self.title = NSLocalizedString(@"textAndTagsTitle", nil);
    self.view.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    
    BanBu_NavButton *completeButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    completeButton.position = ButtonPositionRight;
    [completeButton addTarget:self action:@selector(sendBroadcast) forControlEvents:UIControlEventTouchUpInside];
    CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 30)].width;
    completeButton.frame=CGRectMake(0, 0, btnLen1+20, 30);
    //    [completeButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    [completeButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    completeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *complete = [[[UIBarButtonItem alloc] initWithCustomView:completeButton] autorelease];
    self.navigationItem.rightBarButtonItem = complete;
    [completeButton release];
    
    aTextView = [[UITextView alloc]initWithFrame:CGRectMake( 0, 5, 320, 180)];
    aTextView.backgroundColor = [UIColor clearColor];
    aTextView.delegate = self;
    aTextView.tag = 1001;
    aTextView.font = [UIFont boldSystemFontOfSize:14];
    [aTextView becomeFirstResponder];
    [self.view addSubview:aTextView];
    [aTextView release];
    placeLabel = [[UILabel alloc]initWithFrame:CGRectMake( 10, 13, 310, 18)];
    placeLabel.text = NSLocalizedString(@"writeSomething", nil);
    placeLabel.textColor = [UIColor lightGrayColor];
    placeLabel.backgroundColor = [UIColor clearColor];
    placeLabel.font = [UIFont boldSystemFontOfSize:14];
    [self.view addSubview:placeLabel];
    [placeLabel release];
    
    UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, __MainScreen_Height-44-216-90, 320, 90)];
    aView.backgroundColor = [UIColor clearColor];
    self.functionView = aView;
    [self.view addSubview:aView];
    [aView release];
  
//    //分享栏
//    UIView *shareView = [[UIView alloc]initWithFrame:CGRectMake(0, 90-44, 320, 44)];
//    shareView.backgroundColor = [UIColor colorWithRed:210.0/256 green:210.0/256 blue:210.0/256 alpha:1.0];
//    [self.functionView addSubview:shareView];
//    [shareView release];
//    UILabel *shareLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 7, 60, 30)];
//    shareLabel.text = NSLocalizedString(@"share_broadcast", nil);
//    shareLabel.font = [UIFont systemFontOfSize:14];
//    shareLabel.backgroundColor = [UIColor clearColor];
//    [shareView addSubview:shareLabel];
//    [shareLabel release];
//    NSString *langauage=[MyAppDataManager getPreferredLanguage];
//    for(int i=0;i<2;i++){
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.tag = i;
//        button.frame = CGRectMake(70+i*42, 6, 32, 32);
//        //                隐藏分享
//        /**/
//        button.hidden = YES;
//        /**/
//        if([langauage isEqual:@"zh-Hans"]){
//            if(i){
//                [button setImage:[UIImage imageNamed:@"tencent_bw.png"] forState:UIControlStateNormal];
//                [button setImage:[UIImage imageNamed:@"tencent_down.png"] forState:UIControlStateHighlighted];
//                
//            }else{
//                [button setImage:[UIImage imageNamed:@"sina_bw.png"] forState:UIControlStateNormal];
//                [button setImage:[UIImage imageNamed:@"sina_down.png"] forState:UIControlStateHighlighted];
//                
//            }
//        }else{
//            if(i){
//                [button setImage:[UIImage imageNamed:@"facebook_bw.png"] forState:UIControlStateNormal];
//                [button setImage:[UIImage imageNamed:@"facebook_down.png"] forState:UIControlStateHighlighted];
//            }else{
//                [button setImage:[UIImage imageNamed:@"twitter_bw.png"] forState:UIControlStateNormal];
//                [button setImage:[UIImage imageNamed:@"twitter_down.png"] forState:UIControlStateHighlighted];
//                
//            }
//            
//        }
//        [button addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
//        [shareView addSubview:button];
//        
//    }
//    //根据是否绑定了，来控制分享按钮的显示
//    if([langauage isEqual:@"zh-Hans"]){
//        
//        if([[UserDefaults valueForKey:@"QUser"] length]){
//            UIButton *tempButton = (UIButton *)[[[self.functionView.subviews objectAtIndex:0] subviews] objectAtIndex:2];
//            [self performSelector:@selector(shareAction:) withObject:tempButton];
//        }
//        if([[UserDefaults valueForKey:@"sinaUser"] length]){
//            UIButton *tempButton = (UIButton *)[[[self.functionView.subviews objectAtIndex:0] subviews] objectAtIndex:1];
//            [self performSelector:@selector(shareAction:) withObject:tempButton];
//        }
//    }else{
//        
//        if([[UserDefaults valueForKey:@"FBUser"]length]){
//            UIButton *tempButton = (UIButton *)[[[self.functionView.subviews objectAtIndex:0] subviews] objectAtIndex:2];
//            [self performSelector:@selector(shareAction:) withObject:tempButton];
//        }
//        
//        if([[UserDefaults valueForKey:@"TUser"] length]){
//            UIButton *tempButton = (UIButton *)[[[self.functionView.subviews objectAtIndex:0] subviews] objectAtIndex:1];
//            [self performSelector:@selector(shareAction:) withObject:tempButton];
//        }
//        
//    }
    //2014年10月29日13:53:56 by 张毅飞 魔法广播按钮⬇️
    
    UIButton * magicBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    magicBtn.frame=CGRectMake(100, 45, 120, 30);
    [magicBtn addTarget:self action:@selector(pushToMagicCast) forControlEvents:UIControlEventTouchUpInside];
    [magicBtn setTitle:NSLocalizedString(@"magicWords", nil) forState:UIControlStateNormal];
    [magicBtn setBackgroundImage:[UIImage imageNamed:@"icon_msgpend1.png"] forState:UIControlStateNormal];
    [magicBtn.layer setMasksToBounds:YES];
    [magicBtn.layer setCornerRadius:15];
    [_functionView addSubview:magicBtn];
    
    //标签栏之上
    UILabel *aline = [[UILabel alloc]initWithFrame:CGRectMake(0, -5, 320, 1)];
    aline.backgroundColor = [UIColor colorWithRed:200.0/256 green:200.0/256 blue:200.0/256 alpha:1.0];
    [self.functionView addSubview:aline];
    [aline release];
    
    //标签栏
    UIView *tagView = [[UIView alloc]initWithFrame:CGRectMake(0, 1, 320, 36)];
    tagView.backgroundColor = [UIColor clearColor];
    [self.functionView addSubview:tagView];
    [tagView release];
    UILabel *tagLabel = [[UILabel alloc]initWithFrame:CGRectMake( 10, 5, 55, 30)];
    tagLabel.text = [NSString stringWithFormat:@"%@:",NSLocalizedString(@"tagTextfield",nil)];
    tagLabel.font = [UIFont systemFontOfSize:14];
    tagLabel.backgroundColor = [UIColor clearColor];
    [tagView addSubview:tagLabel];
    [tagLabel release];
    tagTextField = [[UITextField alloc]initWithFrame:CGRectMake(65, 5, 160+85, 30)];
    tagTextField.placeholder = NSLocalizedString(@"tagTextPlaceholder", nil);
    tagTextField.delegate = self;
    tagTextField.backgroundColor = [UIColor whiteColor];
    tagTextField.textColor = [UIColor blackColor];
    [tagTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
    tagTextField.font = [UIFont systemFontOfSize:13];
    
    tagTextField.layer.borderColor = [[UIColor blackColor] CGColor];
    tagTextField.layer.borderWidth = 1.0;
    [tagView addSubview:tagTextField];
    [tagTextField release];
    
    UILabel *paddingView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 5, 30)];
    paddingView.backgroundColor = [UIColor clearColor];
    tagTextField.leftView = paddingView;
    tagTextField.leftViewMode = UITextFieldViewModeAlways;
    [paddingView release];
    
    //监听键盘高度
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShowNotify:) name:UIKeyboardWillShowNotification object:nil];
    
}
#pragma mark - 魔法文字编辑界面
-(void)pushToMagicCast
{
    BanBu_MagicCastViewController * magicCast =[[BanBu_MagicCastViewController alloc]initWithImageData:_imageData WithVoiceData:_soundData WithVoiceTime:_soundTime];
    [self.navigationController pushViewController:magicCast animated:YES];
    [magicCast release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithSendImage:(NSData *)aImageData andSoundData:(NSData *)aSoundData andSoundDuration:(NSString *)duration{

    self = [super init];
    if(self){
        
        _imageData = [[NSData alloc]initWithData:aImageData];
        if(aSoundData){
            _soundData = [[NSData alloc]initWithData:aSoundData];
            _soundTime = [[NSString alloc]initWithString:duration];
        }
    }
    return self;
}


#pragma mark  - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{

    
    if(textView.text.length !=0){
        if(textView.text.length == 1)
        {
            if([textView.text isEqualToString:@" "] || [textView.text isEqualToString:@"\n"]){
                aTextView.text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                return;
            }
        }
        [placeLabel setHidden:YES];
    }else{
        [placeLabel setHidden:NO];
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        return NO;
    }
    if(textView.text.length>200)
    {
        textView.text = [textView.text substringToIndex:200];
        return NO;
    }
    return YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField.text.length > 50)
    {
        textField.text = [textField.text substringToIndex:50];
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"twentyEnough", nil) activityAnimated:NO duration:1.0];
        return NO;
    }
    return YES;
    
}
//-(void)popself
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
//

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//上传图片

-(void)sendPicture{
    
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [sendDic setValue:@"jpg" forKey:@"extname"];
    [AppComManager uploadBanBuBroadcastMedia:_imageData mediaName:@"tupian.jpg" par:sendDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
//    [aTextView becomeFirstResponder];

}

//上传语音

-(void)sendSound{
    
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [sendDic setValue:@"amr" forKey:@"extname"];
    [AppComManager uploadBanBuBroadcastMedia:_soundData mediaName:@"yuyin.amr" par:sendDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
//    [aTextView becomeFirstResponder];

}

//将返回的图片、语音字符串进行包装，和文字一起发送出去。
//标签是包在“saytext”里的


- (void) performPublishAction:(void (^)(void)) action {
    // we defer request for permission to post to the moment of post, then we check for the permission
    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
        // if we don't already have the permission, then we request it now
        [FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                                   defaultAudience:FBSessionDefaultAudienceFriends
                                                 completionHandler:^(FBSession *session, NSError *error) {
                                                     if (!error) {
//                                                         [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
                                                         
                                                         action();
                                                     }
                                                     //For this example, ignore errors (such as if user cancels).
                                                 }];
    } else {
//        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
        
        action();
    }
    
}
 
-(void)sendMessage
{
    NSMutableDictionary *aBroadcastDic = [NSMutableDictionary dictionaryWithCapacity:2];
    NSMutableArray *attachArray = [NSMutableArray arrayWithObject:[NSDictionary dictionaryWithObjectsAndKeys:@"image",@"type",_imageString,@"content", nil]];
    if(_soundString){
        
        [attachArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"sound",@"type",_soundString,@"content",_soundTime,@"length", nil]];
    }
    
    
    if([tagTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length){
        NSArray *charArr = [NSArray arrayWithObjects:@".",@"。",@",",@"，",@"?",@"？",@"/",@"、",@"'",@"’",@"\"",@"“",@";",@"；",@"[",@"]",@"!",@"！",@":",@"：",@"(",@")",@"（",@"）",@"$",@"￥",@"&",@"-",@"／", nil];
        for(NSString *tempStr in charArr){
            tagTextField.text = [tagTextField.text stringByReplacingOccurrencesOfString:tempStr withString:@" "];
            
        }
        //        NSLog(@"%@",tagTextField.text);
        NSMutableArray *tagArr = [NSMutableArray arrayWithArray:[tagTextField.text componentsSeparatedByString:@" "]];
        [tagArr removeObject:@""];
        
        if(tagArr.count){
            //标签去重
            for(int i=0;i<tagArr.count;i++){
                
                for(int j=i+1;j<tagArr.count;j++){
                    
                    
                    if([[tagArr objectAtIndex:i] length]>16)
                    {
                        NSString *str = [NSString stringWithString:[tagArr objectAtIndex:i]];
                        str = [str substringToIndex:16];
                        [tagArr removeObjectAtIndex:i];
                        [tagArr insertObject:str atIndex:i];
                    }
                    if([[tagArr objectAtIndex:j] length]>16)
                    {
                        NSString *str = [NSString stringWithString:[tagArr objectAtIndex:j]];
                        str = [str substringToIndex:16];
                        [tagArr removeObjectAtIndex:j];
                        [tagArr insertObject:str atIndex:j];
                    }

                    if([[tagArr objectAtIndex:i] isEqualToString:[tagArr objectAtIndex:j]]){
                        
                        [tagArr removeObjectAtIndex:j];
                        
                    }
                }
                
            }

            if(tagArr.count>10)
            {
                [tagArr removeObjectsInRange:NSMakeRange(10, tagArr.count-10)];
            }
            NSMutableString *joinStr = [NSMutableString stringWithString:[tagArr objectAtIndex:0]];
            for(int i=1;i<tagArr.count;i++){
                [joinStr appendFormat:@" %@",[tagArr objectAtIndex:i]];
            }
            //        NSLog(@"%@",joinStr);
            
            [aBroadcastDic setValue:[MyAppDataManager IsMinGanWord:[NSString stringWithFormat:@"%@<--%@-->",aTextView.text,joinStr]] forKey:@"saytext"];
            
            
        }

        
    }
    else{
//        //增加电话功能

        [aBroadcastDic setValue:aTextView.text forKey:@"saytext"];

    }
    [aBroadcastDic setValue:attachArray forKey:@"attach"];
     NSDictionary *sendDic = [NSDictionary dictionaryWithObject:aBroadcastDic forKey:@"says"];
    [AppComManager getBanBuData:BanBu_Send_Broadcast par:sendDic delegate:self];
    
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
//    [aTextView becomeFirstResponder];

}

-(void)sendBroadcast{
    //先上传图片，再传语音，最后发送广播
    if([aTextView isFirstResponder]){
        [aTextView resignFirstResponder];

    }
    if(tagTextField.text.length>50)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"tagTextPlaceholder", nil) activityAnimated:NO duration:1];
        return;
    }
    
    if(_soundData || aTextView.text.length){
    
        if(!_imageString){
            [self sendPicture];
            return;
        }
        if(!_soundString && _soundData){
            [self sendSound];
            return;
        }
        //    [self sendMessage];
    }else{
        
        if(!aTextView.text.length){
            
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"voiceOrTextNotice", nil) activityAnimated:NO duration:1.0];
        }
        
    }
}


-(void)keyboardShowNotify:(NSNotification *)notification{
    
    CGFloat keyboardHeight = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;
//    NSLog(@"%f,%@",keyboardHeight,notification.name);
        CGRect frame = self.functionView.frame;
        frame.origin.y = __MainScreen_Height-44-90-keyboardHeight;
        self.functionView.frame = frame;
    
}

#pragma mark - AlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
//    if(buttonIndex == 1){
//        
//        BanBu_MyProfileViewController *profile = [[BanBu_MyProfileViewController alloc]autorelease];
//        profile.tableView.contentOffset = CGPointMake(0, 360);
//        [self.navigationController pushViewController:profile animated:YES];
//    }
}

#pragma mark - BanBuUploadRequsetDelegate

- (void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:NO afterShow:0.0];
    if(error){
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:2.0];
    }
    if([[resDic valueForKey:@"ok"] boolValue]){
        if([[resDic valueForKey:@"requestname"] isEqualToString:@"tupian.jpg"]){
            if(_imageString){
                [_imageString release];
            }
            _imageString = [[NSString alloc]initWithString:[resDic valueForKey:@"fileurl"]];
            if(_soundData){
                [self sendSound];
            }else{
                [self sendMessage];
            }
        }else{
            if(_soundString){
                [_soundString release];
            }
            _soundString = [[NSString alloc]initWithString:[resDic valueForKey:@"fileurl"]];
            [FileManager removeItemAtPath:[AppComManager pathForMedia:@"yuyin.amr"] error:nil];
            [self sendMessage];
        }
    }
}

#pragma mark - BanBuRequestDelegate

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error{
//    NSLog(@"%@",resDic);
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        return;
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Send_Broadcast]){
        if([[resDic valueForKey:@"ok"] isEqual:@"y"])
        {
            NSNumber * number = [NSNumber numberWithInt:[[resDic valueForKey:@"getscore"] integerValue]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [MyAppDataManager showGoldView:number andView:self.navigationController.view];
            });
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"releaseSuccess", nil) activityAnimated:NO duration:1.0];
           
            [self performSelector:@selector(backLast) withObject:self afterDelay:1.0];
            
        }
        else
        {
            if([[resDic valueForKey:@"error"] length])
            {
//                if([[resDic valueForKey:@"error"]isEqual:@"__interfacelimit__"])
//                {
                    [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1];
//                }
            }
        }
    }
   
}

-(void)backLast{
    for(BanBu_BroadcastTVC *v in self.navigationController.viewControllers)
    {
        if([v isKindOfClass:[BanBu_BroadcastTVC class]])
        {
            [v setRefreshing];
        }
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}





@end
